package test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yzy on 2020-02-16 10:44
 */
public class OnlineJudge2 {


    private static volatile int idx = 0;
    private static String TEST_STR = "This is example String";
    private static int STR_LEN = TEST_STR.length();

    public static void main(String[] args) throws InterruptedException {
        StringPrint sp = new StringPrint();
        new Thread(() ->{
            while(idx < STR_LEN){
                try {
                    sp.printChar("A",0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        new Thread(() ->{
            while(idx < STR_LEN){
                try {
                    sp.printChar("B",1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    public static class StringPrint{
        private Lock lock = new ReentrantLock();
        private Condition con = lock.newCondition();

        public void printChar(String threadName, int flag) throws InterruptedException {
            lock.lock();
            try {
                while(idx%2 != flag){
                    con.await();
                }
                if(idx >= STR_LEN){
                    return;
                }
                System.out.println(threadName + ":" + TEST_STR.charAt(idx));
                idx++;
                con.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }

}
